//
//  SCLoginController.m
//  Mutal
//
//  Created by TonyStart on 16/10/24.
//  Copyright © 2016年 com.wx. All rights reserved.
//

#import "SCLoginController.h"
#import "SCRegisterController.h"
#import "UIAlertController+SCAlertController.h"
#import "SCUserInfoViewModel.h"
#import "SCMainTabBar.h"
#import "SCMessageController.h"
#import "SCCoverView.h"
#import "NSData+ImageContentType.h"
#import "SCUserInfo.h"
@interface SCLoginController ()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *userPassword;
@property(nonatomic,strong)SCCoverView *coverView;
@end

@implementation SCLoginController


- (void)viewDidLoad {
    [super viewDidLoad];
    
}
-(SCCoverView *)coverView{
    if (!_coverView) {
        _coverView = [[SCCoverView alloc] init];
    }
    return _coverView;
    
}
-(void)viewDidAppear:(BOOL)animated{

    _userName.leftView = [self getTextFieldLeftView:@"icon-手机"];
    _userName.leftViewMode = UITextFieldViewModeAlways;
    _userName.clearButtonMode = UITextFieldViewModeWhileEditing;
    _userPassword.leftView = [self getTextFieldLeftView:@"icon-钥匙"];
    _userPassword.leftViewMode = UITextFieldViewModeAlways;
    _userPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
}
-(UIView*)getTextFieldLeftView:(NSString*)imgStr{
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _userName.bounds.size.height, _userName.bounds.size.height)];
    UIImageView *imgV= [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
    imgV.image = [UIImage imageNamed:imgStr];
    
    UIImageView *lineImg = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imgV.frame)+5, 5, 1, 30)];
    lineImg.image = [UIImage imageNamed:@"分割线"];
    
    [leftView addSubview:imgV];
    [leftView addSubview:lineImg];
    
    return leftView;
}
- (IBAction)loginClick:(id)sender {
    NSString *name = self.userName.text;
    NSString *password = self.userPassword.text;
    if ([name isEqualToString:@""]||[password isEqualToString:@""]) {
        UIAlertController *alerC = [UIAlertController scAlertWithTitle:@"提示" msg:@"用户或者密码不能为空"];
        
        [self presentViewController:alerC animated:YES completion:^{
            
        }];
        return;
    }
    if (name.length<11) {
        UIAlertController *alerC = [UIAlertController scAlertWithTitle:@"提示" msg:@"请输入正确的手机号码"];
        
        [self presentViewController:alerC animated:YES completion:^{
            
        }];
        return;
    }
    //发送网络请求
    SCUserInfoViewModel *userInfoViewModel = [[SCUserInfoViewModel alloc] init];
    
    [userInfoViewModel requestUserLoginWithName:name password:password finish:^(id data, NSInteger code) {
        //如果CODE不等200 提示错误
        if (code != 200) {
            UIAlertController *alerC = [UIAlertController scAlertWithTitle:@"提示" msg:data];
            
            [self presentViewController:alerC animated:YES completion:^{
                
            }];
            return;
        }else{
            //登录成功 跳转到主界面中去
            if (data) {
                //将用户数据数据写入沙盒
                
                //拼接网络图片完整路径
                
                NSString *imgPath = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu%@",data[@"avatar"]];
                NSURL *url = [NSURL URLWithString:imgPath];
                
                
                [[UIApplication sharedApplication].keyWindow addSubview:self.coverView];
                //耗时操作 放入多线程中
                dispatch_async(dispatch_get_global_queue(0, 0),^{
                    //将图片转换为NSData
                    NSData *imgData = [NSData dataWithContentsOfURL:url];
                    NSString *fileName = nil;
                    
                    //如果图片不为空 将图片存入沙盒
                    if (imgData) {
                        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                        //判断图片是什么格式的
                        NSString *imgType=[NSData sd_contentTypeForImageData:imgData];
                        
                        NSString *imgSuffix = nil;
                        if ([imgType isEqualToString:@"image/jpeg"]) {
                            imgSuffix = @"jpg";
                        }else if([imgType isEqualToString:@"image/png"]){
                            imgSuffix = @"png";
                        }else if ([imgType isEqualToString:@"image/gif"]){
                            imgSuffix = @"gif";
                        }
                        fileName = [NSString stringWithFormat:@"pic.%@",imgSuffix];
                        //拼接图片保存路径
                        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
                        //写入沙盒中
                        [[NSFileManager defaultManager] createFileAtPath:filePath contents:imgData attributes:nil];
                        
                        
                    }
                    //本地缓存数据
                    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                    [userDefault setBool:YES forKey:@"is_login"];
                    [userDefault synchronize];
                    
                    NSDictionary *userInfoDict = @{@"avatar":fileName,@"id":data[@"id"],@"user_nicename":data[@"nick_name"],@"mobile":data[@"mobile"]};
                    [SCUserInfo defaultUser].userInfo = [SCUserInfoModel userInfoWithDict:userInfoDict];
                    [userInfoDict writeToFile:[NSHomeDirectory() stringByAppendingString:@"/Documents/userInfo.plist"]  atomically:YES];
                    //回到主线程中 返回主界面
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
                        [self.coverView removeFromSuperview];
                        if ([rootVC isKindOfClass:[SCMainTabBar class]]) {
                            SCMainTabBar *mainVC = (SCMainTabBar*)rootVC;
                            mainVC.selectedIndex = 0;
                        }
                        [self.navigationController popViewControllerAnimated:NO];
                    });
                });

            }
        }
        
    }];
    
}
- (IBAction)findBackPassClick:(id)sender {
}

- (IBAction)registerClick:(id)sender {
    SCRegisterController *registerVC = [UIStoryboard storyboardWithName:@"RegisterStoryboard" bundle:nil].instantiateInitialViewController;
    
    [self.navigationController pushViewController:registerVC animated:NO];
}

- (IBAction)backUpClick:(id)sender {
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    NSArray *vcs = self.navigationController.viewControllers;

    UIViewController *pushVC = vcs[vcs.count-2];
    //如果是从message控制器来的话 点击返回按钮则直接切换tabbar的selectIndex
    if ([pushVC isKindOfClass:[SCMessageController class]]) {
        
        
        if ([rootVC isKindOfClass:[SCMainTabBar class]]) {
            SCMainTabBar *mainTabBar = (SCMainTabBar*)rootVC;
            mainTabBar.selectedIndex = 0;
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
